package com.cheng.system.controller;


import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.cheng.common.annotation.JWTIgnore;
import com.cheng.common.domain.BaseSearchVO;
import com.cheng.common.domain.R;
import com.cheng.system.model.User;
import com.cheng.system.service.impl.RoleServiceImpl;
import com.cheng.system.service.impl.UserServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 起凡
 * @since 2021-09-25
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    RoleServiceImpl roleService;

    @GetMapping("/list")
    public R<PageInfo<User>> list(BaseSearchVO searchVO) {
        PageHelper.startPage(searchVO.getPageNum(), searchVO.getPageSize());
        return R.ok(new PageInfo<>(userService.getBaseMapper().listUser(searchVO)));
    }

    @GetMapping("delete")
    public R<Boolean> delete(@RequestParam Long id) {
        userService.removeById(id);
        return R.ok(true);
    }

    @PostMapping("/save")
    public R<Boolean> save(@RequestBody @Validated User user) {
        userService.save(user);
        return R.ok(true);
    }

    @GetMapping("getUserInfo")
    public R<User> getUserInfo() {
        User user = userService.getBaseMapper().getUser(StpUtil.getLoginIdAsLong());
        if (user == null) {
            throw new NotLoginException("登录会话失效，请重新登录", "", "");
        }
        user.setPassword(null);

        return R.ok(user);
    }

    @PostMapping("update")
    public R<Boolean> update(@RequestBody User user) {
        user.setOpenId(null).setPassword(null)
                .setUserName(null).setLoginDate(null)
                .setLoginIp(null)
                .setDeleted(null)
                .setTotalMoney(null)
                .setUserType(null)
                .setUpdateTime(null)
                .setUpdateBy(null)
                .setRemark(null);
        userService.updateById(user);
        return R.ok(true);
    }

    @JWTIgnore
    @GetMapping("/get")
    @SaCheckRole("admin")
    public R<User> get(Long userId) {
        return R.ok(userService.getBaseMapper().getUser(userId));
    }
}

